import { defineStore } from 'pinia';
import axiosInstance from '../api/axiosInstance';
import { authService } from '../api/authService';

interface User {
  id: number;
  username: string;
  email: string;
  firstName: string;
  lastName: string;
  role: string;
}

interface AuthState {
  token: string | null;
  user: User | null;
  isAuthenticated: boolean;
  loading: boolean;
}

export const useAuthStore = defineStore('auth', {
  state: (): AuthState => ({
    token: localStorage.getItem('token'),
    user: JSON.parse(localStorage.getItem('user') || 'null'),
    isAuthenticated: !!localStorage.getItem('token'),
    loading: false
  }),
  
  // 添加额外的方法来验证token有效性
  actions: {
    // 现有的login, register, logout, setToken, setUser方法保持不变
    
    // 添加一个验证token的方法，在应用启动时调用
    async validateToken() {
      if (this.token && this.isAuthenticated) {
        try {
          // 尝试获取用户信息来验证token是否有效
          const response = await axiosInstance.get('/auth/me');
          this.setUser(response.data);
          return true;
        } catch (error) {
          // token无效，清除认证状态
          this.logout();
          return false;
        }
      }
      return false;
    },

    async login(email: string, password: string) {
      this.loading = true;
      try {
        const response = await authService.login({ email, password });
        this.setUser(response.data.user);
        this.setToken(response.data.token);
        return response;
      } catch (error) {
        throw error;
      } finally {
        this.loading = false;
      }
    },

    async register(userData: any) {
      this.loading = true;
      try {
        const response = await authService.register(userData);
        return response;
      } catch (error) {
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    logout() {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      this.token = null;
      this.user = null;
      this.isAuthenticated = false;
    },
    
    setToken(token: string) {
      this.token = token;
      localStorage.setItem('token', token);
      this.isAuthenticated = true;
    },
    
    setUser(user: User) {
      this.user = user;
      localStorage.setItem('user', JSON.stringify(user));
    }
  }
});